package kr.hkit.powerjava.chapter14.work;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class Interest extends JFrame {

	private JPanel contentPane;
	private JPanel inputPanel;
	private JPanel buttonPanel;
	private JPanel resultPanel;
	private JButton btnChange;
	private InputPanel inputMoney;
	private InputPanel inputInterest;
	private JTextField tfResult;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Interest frame = new Interest();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Interest() {
		initialize();
	}

	private void initialize() {
		setTitle("이자 계산기");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		inputPanel = new JPanel();
		contentPane.add(inputPanel, BorderLayout.NORTH);
		inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));

		inputMoney = new InputPanel(6);
		inputMoney.setLblNewLabel("원금을 입력하시오");
		;
		inputPanel.add(inputMoney);

		inputInterest = new InputPanel(6);
		inputInterest.setLblNewLabel("이율을 입력하시오");
		inputPanel.add(inputInterest);

		buttonPanel = new JPanel();
		contentPane.add(buttonPanel, BorderLayout.CENTER);

		btnChange = new JButton("변환");
		btnChange.addActionListener(new BtnChangeActionListener());
		buttonPanel.add(btnChange);

		resultPanel = new JPanel();
		contentPane.add(resultPanel, BorderLayout.SOUTH);

		tfResult = new JTextField();
		tfResult.setHorizontalAlignment(SwingConstants.CENTER);
		resultPanel.add(tfResult);
		tfResult.setColumns(20);

		pack();
	}

	private class BtnChangeActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("변환")) {
				int money = 0;
				double interest = 0;
				try {
					money = Integer.parseInt(inputMoney.getTextField());
					interest = Double.parseDouble(inputInterest.getTextField());

				} catch (NumberFormatException err) {
					JOptionPane.showMessageDialog(btnChange, "숫자만 가능합니다.");
					inputMoney.setTextField("");
					inputInterest.setTextField("");
				}
				tfResult.setText("이자는 연 " + (int) (money * interest / 100)
						+ "만원 입니다.");
			}
		}
	}
}
